package com.simple.piger.utils;

import com.google.common.collect.Lists;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.simple.piger.config.QiniuConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author baolw
 * @date 2018/2/7 19:31
 * 七牛上传图片
 */
@Component
@Slf4j
public class QiniuUpload {
    @Autowired
    private QiniuConfig qiniuConfig;
    @Value("${qiniu.bucket}")
    private String bucket;

    private static final Configuration cfg = new Configuration(Zone.zone0());
    private static final UploadManager uploadManager = new UploadManager(cfg);

    public UploadManager getUploadManager() {
        return uploadManager;
    }

    @Cacheable(value="userCache")
    public String getFileToken() {
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        String token = auth.uploadToken(qiniuConfig.getBucket());
        return token;
    }

    /**
     * 上传图片到七牛
     *
     * @param bytes
     * @return
     */
    public String uploadByteArray(byte[] bytes, String filename) {
        String token = getFileToken();
        Response response = null;
        try {
            response = uploadManager.put(bytes, filename, token);
            System.out.println(response.bodyString());
            DefaultPutRet putRet = GsonHelper.parseObject(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException e) {
            log.error("上传图片到七牛失败", e);
            return null;
        } finally {
            if (null != response) {
                log.error("七牛Response 关闭");
                response.close();
            }
        }
    }

    /**
     * 批量删除七牛文件
     * //单次批量请求的文件数量不得超过1000
     *
     * @param files
     * @return
     */
    public List<String> deleteBatchFile(List<String> files, Auth auth) throws Exception {
        List<String> result = Lists.newArrayList();
        if (files.size() >= 1000) {
            log.info("单次批量请求的文件数量不得超过1000");
            throw new Exception("单次批量请求的文件数量不得超过1000");
        }
        BucketManager bucketManager = new BucketManager(auth, cfg);
        log.info("开始删除七牛文件，" + GsonHelper.toJson(files));
        deleteBatch(files, result, bucketManager);
        log.info("删除完成");
        return result;
    }

    /**
     * 批量删除七牛文件
     * //单次批量请求的文件数量不得超过1000
     *
     * @param files
     * @return
     */
    public List<String> deleteBatchFile(List<String> files) throws Exception {
        List<String> result = Lists.newArrayList();
        if (files.size() >= 1000) {
            log.info("单次批量请求的文件数量不得超过1000");
            throw new Exception("单次批量请求的文件数量不得超过1000");
        }
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        log.info("开始删除七牛文件，" + GsonHelper.toJson(files));
        deleteBatch(files, result, bucketManager);
        log.info("删除完成");
        return result;
    }

    private void deleteBatch(List<String> files, List<String> result, BucketManager bucketManager) throws Exception {
        try {
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucket, files.toArray(new String[0]));
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < files.size(); i++) {
                BatchStatus status = batchStatusList[i];
                if (status.code == 200) {
                    result.add(files.get(i));
                } else {
                    log.error("删除文件失败，文件路径：" + files.get(i));
                    log.error(status.data.error);
                }
            }
        } catch (QiniuException ex) {
            log.error(ex.response.toString(), ex);
            throw new Exception();
        }
    }

}
